<?php

namespace App\Controller\InsideService;

use App\Model\AdminWord;
use App\Model\QmGameUser;
use App\Model\QmGameVersion;
use App\Model\QmGameWxTask;
use App\Service\MiMasterService;
use App\Service\QmGameService;
use App\Service\SlWechatService;
use App\Service\TiktokPayService;
use GuzzleHttp\Exception\GuzzleException;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Guzzle\ClientFactory;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PostMapping;
use Qcloud\Cos\Client;

#[Controller(prefix: '/sldnfInsideService/GameList')]
class GameListInside extends BaseInside {

    #[Inject]
    protected ClientFactory $clientFactory;

    #[GetMapping(path: 'index')]
    public function index(): array {
        $returnArr = [];
        $gameHash = $this->request->query('game_hash', '');

        if ($gameHash) {
            $returnArr = QmGameService::getGameInfo($gameHash);
        }

        return $this->buildSuccess([
            'list' => $returnArr
        ]);
    }

    /**
     * 获取AccessToken
     * @return array
     * @throws GuzzleException
     */
    #[GetMapping(path: 'access_token')]
    public function accessToken(): array {
        $gameHash = $this->request->query('game_hash', '651da2028476d3e669f892fba5014ebe');

        $gameInfo = QmGameService::getGameInfo($gameHash);
        if ($gameInfo['platform'] == 1) {
            $accessToken = (new MiMasterService())->getAccessToken($gameInfo);
        } else if ($gameInfo['platform'] == 2) {
            $accessToken = (new TiktokPayService())->getAccessToken($gameInfo);
        }

        return $this->buildSuccess([
            'access_token' => $accessToken
        ]);
    }

    /**
     * 文本合规检测
     * 肆狼项目不直接与微信对接
     * @throws GuzzleException
     */
    #[PostMapping(path: 'check_msg')]
    public function checkMsg(): array {
        $gameHash = $this->request->post('game_hash', '');
        $msg = $this->request->post('msg', '');
        $openid = $this->request->post('openid', '');

        $gameInfo = QmGameService::getGameInfo($gameHash);
        if ($gameInfo['platform'] == 1) {
            $accessToken = (new MiMasterService())->checkMsg($gameInfo, ['openid' => $openid], $msg);
        } else if ($gameInfo['platform'] == 2) {
//            $accessToken = (new TiktokPayService())->checkMsg($gameInfo, [], $msg);
            $accessToken = true;
        }

        return $this->buildSuccess([
            'check' => $accessToken
        ]);
    }

    /**
     * 文本合规检测 新 37屏蔽词库和本地屏蔽检查
     * @throws GuzzleException
     */
    #[PostMapping(path: 'check_msg_new')]
    public function checkMsgNew(): array {
        $postData = $this->request->post();
        $check = (new SlWechatService())->checkWord($postData);
        return $this->buildSuccess([
            'check' => $check
        ]);
    }

    /**
     * 头像合规检测
     * @throws GuzzleException
     */
    #[PostMapping(path: 'check_avatar')]
    public function checkAvatar(): array {
        $gameHash = $this->request->post('game_hash', '');
        $avatar_url = $this->request->post('avatar_url', '');
        $openid = $this->request->post('openid', '');
        $version = $this->request->post('version', '');

        $result = false;
        $gameInfo = QmGameService::getGameInfo($gameHash);
        if ($gameInfo['platform'] == 1) {
            $accessToken = (new MiMasterService())->checkAvatar($gameInfo, ['openid' => $openid], $avatar_url);
            if (isset($accessToken['errcode']) && $accessToken['errcode'] == 0) {
                //发送成功 添加记录
                $model = new QmGameWxTask();
                $model->game_hash = $gameHash;
                $model->openid = $openid;
                $model->version = $version;
                $model->media_type = 2;
                $model->media_url = $avatar_url;
                $model->trace_id = $accessToken['trace_id'];
                $model->status = 0;
                $model->save();
                $result = true;
            }
        } else if ($gameInfo['platform'] == 2) {
//            $accessToken = (new TiktokPayService())->checkAvatar($gameInfo, [], $msg);
            $result = true;
        }

        return $this->buildSuccess([
            'check' => $result
        ]);
    }

    #[PostMapping(path: 'syncUser')]
    public function syncUser(): array {
        $uid = $this->request->post('uid', '');
        $uuid = $this->request->post('uuid', '');
        $openid = $this->request->post('openid', '');
        $nickname = $this->request->post('nickname', '');
        $game_hash = $this->request->post('game_hash', '');
        $avatar_url = $this->request->post('avatar_url', '');
        $vip = $this->request->post('vip', '');
        $vip_cost = $this->request->post('vip_cost', '');
        $coin = $this->request->post('coin', '');

        $model = QmGameUser::query()
            ->where('uid', $uid)->where('game_hash', $game_hash)->first();
        if ($model) {
            $model->avatar_url = $avatar_url;
            $model->nickname = $nickname;
            $model->vip = $vip;
            $model->vip_cost = $vip_cost;
            $model->coin = $coin;
            $model->last_login_at = date('Y-m-d H:i:s');
            $model->save();
        } else {
            $model = new QmGameUser();
            $model->uid = $uid;
            $model->openid = $openid;
            $model->nickname = $nickname;
            $model->avatar_url = $avatar_url;
            $model->uuid = $uuid;
            $model->vip = $vip;
            $model->vip_cost = $vip_cost;
            $model->coin = $coin;
            $model->game_hash = $game_hash;
            $model->last_login_at = date('Y-m-d H:i:s');
            $model->save();
        }
        return $this->buildSuccess();
    }

    #[PostMapping(path: 'shareToCos')]
    public function shareToCos(): array {
        $game_hash = $this->request->post('game_hash', '');
        $avatar = $this->request->post('avatar_url', '');
        $cosClient = new Client([
            'region'      => config('qcloud.region'),
            'schema'      => 'https',
            'credentials' => [
                'secretId'  => config('qcloud.secretId'),
                'secretKey' => config('qcloud.secretKey')
            ]
        ]);
        $domain = 'https://commoncdn.qingmanet.com';
        $avatar_url = '';
        if ($avatar) {
            $rootPath = '/data/share';
            $avaPath = DIRECTORY_SEPARATOR . 'avatar' . DIRECTORY_SEPARATOR . $game_hash . DIRECTORY_SEPARATOR . date('Ymd') . DIRECTORY_SEPARATOR;
            $localUrl = $rootPath . $avaPath . md5($avatar) . '.jpg';
            if (!file_exists($localUrl)) {
                if (!file_exists($rootPath . $avaPath)) {
                    mkdir($rootPath . $avaPath, 0755, true);
                }
                $client = $this->clientFactory->create(['verify' => false]);
                if (str_starts_with($avatar, 'http://') || str_starts_with($avatar, 'https://')) {
                    $response = $client->get($avatar, [
                        'sink' => $localUrl
                    ]);
                    if ($response->getStatusCode() == 200) {
                        $cosClient->upload(
                            config('qcloud.blucket'),
                            $avaPath . md5($avatar) . '.jpg',
                            $response->getBody()
                        );
                        $avatar_url = $domain . $avaPath . md5($avatar) . '.jpg';
                    }
                }
            } else {
                $avatar_url = $domain . $avaPath . md5($avatar) . '.jpg';
            }

        }
        return $this->buildSuccess([$avatar_url]);
    }
}